<template>
  <div class="real-name">
    <el-card>
      <template #header>
        <h2>实名认证信息</h2>
      </template>
      <div class="real-info">
        <div class="real-tip">
          <el-icon>
            <InfoFilled/>
          </el-icon>
          <p>完成实名认证后即可添加就诊人并进行正常挂号，为不影响您的正常就诊，建议提前完成实名认证。</p>
        </div>

        <!-- 认证表单：认证成功的、认证失败的-->
        <div class="real-form" v-if="userInfo.authStatus === 0">
          <!-- 认证完成之后的表单-->
          <el-descriptions
              class="margin-top"
              :column="1"
              size="small"
              border
              style="margin: 20px;"
              label-width=150px
          >
            <el-descriptions-item label-align="center">
              <template #label>
                <div class="cell-item">
                  <el-icon>
                    <User/>
                  </el-icon>
                  用户姓名
                </div>
              </template>
              <!-- 黎优 -->
              {{ userInfo.name }}
            </el-descriptions-item>
            <el-descriptions-item label-align="center">
              <template #label>
                <div class="cell-item">
                  <el-icon>
                    <Postcard/>
                  </el-icon>
                  证件类型
                </div>
              </template>
              {{ userInfo.certificatesType === 20 ? '户口本' : '身份证' }}
            </el-descriptions-item>
            <el-descriptions-item label-align="center">
              <template #label>
                <div class="cell-item">
                  <el-icon>
                    <ChatRound/>
                  </el-icon>
                  证件号码
                </div>
              </template>
              {{ userInfo.certificatesNo }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 还未认证的表单-->
        <div v-else style="margin-top: 20px;width: 100%; display: flex; justify-content: center;">
          <el-form ref="formRef" :rules="rules" :model="params" style="width: 60%;">
            <el-form-item label="用户姓名" prop="name">
              <el-input v-model="params.name" placeholder="请输入用户姓名"></el-input>
            </el-form-item>
            <el-form-item label="证件类型" prop="certificatesType">
              <el-select v-model="params.certificatesType" placeholder="请选择证件类型">
                <el-option
                    v-for="(item,index) in certificationType"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="证件号码" prop="certificatesNo">
              <el-input v-model="params.certificatesNo" placeholder="请输入证件号码"></el-input>
            </el-form-item>
            <el-form-item label="上传证件" prop="certificatesUrl">
              <el-upload
                  ref="upload"
                  list-type="picture-card"
                  :on-remove="handleRemove"
                  :on-preview="handlePicturePreview"
                  :on-success="handlerSuccess"
                  :on-exceed="handleExceed"
                  :limit="1"
                  action="/api/oss/file/fileUpload?fileHost=userAuah"
              >
                <img src="../../assets/images/auth_example.png" alt="example" style="width: 100%;"/>
              </el-upload>

              <el-dialog v-model="dialogVisible">
                <img
                    v-if="params.certificatesUrl"
                    style="width: 100%; height: 100%"
                    :src="params.certificatesUrl"
                    alt="Preview Image"
                />
              </el-dialog>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="default" @click="submit">提交</el-button>
              <el-button type="primary" size="default" @click="reset">重写</el-button>
            </el-form-item>
          </el-form>

        </div>

      </div>
    </el-card>
  </div>
</template>


<script setup>
import {ref, onMounted, reactive} from "vue";
import {ChatRound, InfoFilled, Plus, Postcard, User} from "@element-plus/icons-vue";
import {reqUserInfo, reqCertationType, reqUserCertation} from "@/api/user/index.js";
import {ElMessage} from "element-plus";
// 实名认证表单验证方法
const validatorName = (rule, value, callback) => {
  const reg = /^[\u00B7\u3007\u3400-\u4DBF\u4E00-\u9FFF\uE000-\uF8FF\uD840-\uD8C0\uDC00-\uDFFF\uF900-\uFAFF]+$/;
  if (reg.test(value)) {
    callback();
  } else {
    callback(new Error("请输入中文姓名"));
  }
};
const validatorCertificationType = (rule, value, callback) => {
  if (value === "10" || value === "20") {
    callback();
  } else {
    callback(new Error("请选择证件类型"));
  }
};
const validatorCertificationNo = (rule, value, callback) => {
  const sfz = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$/;
  const hkb = /^\d{9}$/;
  if (sfz.test(value) || hkb.test(value)) {
    callback();
  } else {
    callback(new Error("请输入正确的证件号码"));
  }
};
const validatorCerUrl = (rule, value, callback) => {
  if (value.length) {
    callback();
  } else {
    callback(new Error("请上传证件照片"));
  }
};

//实名认证表单数据
const params = reactive({
  name: "",
  certificatesType: "",
  certificatesNo: "",
  certificatesUrl: ""
});

// 组件挂载时获取用户信息是否认证过的状态
onMounted(() => {
  getUserInfoStatus();
  getCertificationType();
});


const formRef = ref(null);
// 实名认证表单验证规则
const rules = {
  name: [
    {required: true, validator: validatorName, trigger: "blur"}
  ],
  certificatesType: [
    {required: true, validator: validatorCertificationType, trigger: "change"}
  ],
  certificatesNo: [
    {required: true, validator: validatorCertificationNo, trigger: "blur"}
  ],
  certificatesUrl: [
    {required: true, validator: validatorCerUrl, trigger: "change"}
  ]
};


// 获取用户信息
const userInfo = ref({});
const getUserInfoStatus = async () => {
  const res = await reqUserInfo();
  if (res.code === 200) {
    userInfo.value = res.data;
  }
};

// 获取证件类型
const certificationType = ref([]);
const getCertificationType = async () => {
  const res = await reqCertationType();
  if (res.code === 200) {
    certificationType.value = res.data;
  }
};

//提交表单
const submit = async () => {
  // 表单验证
  const isValid = await formRef.value.validate();
  if (!isValid) {
    ElMessage.error("请检查输入项！");
  }
  try {
    await reqUserCertation(params);
    ElMessage.success("实名认证成功！");
    getUserInfoStatus();
  } catch (error) {
    ElMessage.error("实名认证失败，请重新提交！");
  }
};


//重置表单
const upload = ref(null);
const reset = () => {
  params.name = "";
  params.certificatesType = "";
  params.certificatesNo = "";
  params.certificatesUrl = "";
  upload.value.clearFiles();
};

const dialogVisible = ref(false);
//上传成功的钩子
const handlerSuccess = (response) => {
  // 上传成功后，将图片地址赋值给表单的图片字段
  params.certificatesUrl = response.data;
}

// 照片墙超过限制的钩子
const handleExceed = () => {
  ElMessage.error("上传图片数量只能为1张！");
  return false;
};

//照片墙预览
const handlePicturePreview = () => {
  //触发预览的钩子的时候，对话框显示
  dialogVisible.value = true;
};

//照片墙删除图片
const handleRemove = () => {
  params.certificatesUrl = "";
};


</script>

<style scoped lang="scss">
.real-name {
  width: 100%;
  margin-top: 20px;
  padding: 20px;
  box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);

  .el-card {
    width: 100%;
    border-radius: 10px;

    .real-info {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 100%;


      .real-tip {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 50px;

        p {
          font-family: "Arial", sans-serif;
          font-size: 16px;
          color: #9b9b9b;
          margin-left: 10px;
        }
      }

      .real-form {
        width: 100%;
        //margin-top: 10px;

        .cell-item {
          width: 100%;
        }
      }
    }
  }
}

</style>